#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2021 4Paradigm
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import pytest
import logging
import sys

from case_conf import OpenMLDB_ZK_CLUSTER, OpenMLDB_ZK_PATH
from openmldb.dbapi import connect
from openmldb.dbapi import DatabaseError

logging.basicConfig(level=logging.WARNING)


class TestOpenmldbDBAPI:

    cursor = None

    @classmethod
    def setup_class(cls):
        db = connect(
            'db_test', OpenMLDB_ZK_CLUSTER, OpenMLDB_ZK_PATH)
        cls.cursor = db.cursor()
        cls.cursor.execute("create database if not exists db_test;")
        cls.cursor.execute('create table new_table (x string, y int);')
        assert "new_table" in cls.cursor.get_all_tables()

    @classmethod
    def teardown_class(cls):
        cls.cursor.execute("drop table new_table;")
        assert "new_table" not in cls.cursor.get_all_tables()

        with pytest.raises(DatabaseError):
            cls.cursor.execute("drop table new_table;")
        cls.cursor.close()

    def test_invalid_create(self):
        with pytest.raises(DatabaseError):
            self.cursor.execute("create table ")

    def test_simple_insert_select(self):
        self.cursor.execute("insert into new_table values('first', 100);")
        result = self.cursor.execute("select * from new_table;").fetchone()
        assert 'first' in result
        assert 100 in result

        with pytest.raises(DatabaseError):
            self.cursor.execute("insert into new_table values(1001, 'first1');")
        with pytest.raises(DatabaseError):
            self.cursor.execute(
                "insert into new_table values({'x':1001, 'y':'first1'});")

    def test_select_conditioned(self):
        self.cursor.execute("insert into new_table values('second', 200);")
        result = self.cursor.execute(
            "select * from new_table where x = 'second';").fetchone()
        assert 'second' in result
        assert 200 in result


if __name__ == "__main__":
    sys.exit(pytest.main(["-vv", "dbapi_test.py"]))
